<template>
  <div class="overrun-page linear-gradient">
    <div style="height: 2vh"></div>
    <el-col>
      <el-container>
        <el-header>
          <div class="common-div-card header-search">
            <el-form :inline="true" :model="searchForm" class="header-search-form">
              <el-form-item label="开始时间">
                <el-date-picker v-model="searchForm.start" type="datetime" placeholder="开始时间" value-format="YYYY-MM-DD HH:mm:ss" />
              </el-form-item>
              <el-form-item label="结束时间">
                <el-date-picker v-model="searchForm.end" type="datetime" placeholder="结束时间" value-format="YYYY-MM-DD HH:mm:ss" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleSearch">查询</el-button>
                <el-button @click="handleReset">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-header>
        <el-main>
          <el-row class="main-table">
            <el-col :span="12">
              <el-row>
                <div style="width: 100%" class="common-div-card main-table-left">
                  <el-table
                    :data="leftTableData"
                    border
                    :header-cell-style="{ background: '#eef1f6', color: '#606266', textAlign: 'center' }"
                    :cell-style="{ textAlign: 'center' }"
                    :stripe="true"
                    v-loading="leftTableLoading"
                    :show-overflow-tooltip="true"
                    ref="tableRef"
                    @row-click="handleRowClick"
                  >
                    <el-table-column type="index" label="序号" width="60" fixed="left" />
                    <!-- <el-table-column prop="entid" label="入口卷号" width="160" /> -->
                    <el-table-column prop="extid" label="出口卷号" width="160" />
                    <el-table-column prop="steelGrade" label="钢种" width="140" />
                    <el-table-column prop="entThk" label="入口厚度" width="120" />
                    <el-table-column prop="entWidth" label="入口宽度" width="120" />
                    <el-table-column prop="speed" label="速度" width="120" />
                    <el-table-column prop="giTem" label="GI锅温度" width="120" />
                    <el-table-column prop="p8Real" label="P8实际值" width="120" />
                    <el-table-column prop="p8Set" label="P8设定值" width="120" />
                    <el-table-column prop="p10Real" label="P10实际值" width="120" />
                    <el-table-column prop="p10Set" label="P10设定值" width="120" />
                    <el-table-column prop="p9Real" label="P9实际值" width="120" />
                    <el-table-column prop="p9Set" label="P9设定值" width="120" />
                    <el-table-column prop="zincLiquidVar" label="锌液方差" width="120" />
                    <el-table-column prop="zincLiquidStd" label="锌液标准差" width="120" />
                    <el-table-column prop="time" label="时间" width="220" />
                  </el-table>
                </div>
              </el-row>
              <el-row>
                <!-- 分页区域 -->
                <div class="common-div-card pagination">
                  <el-pagination
                    v-model:current-page="pagination.currentPage"
                    v-model:page-size="pagination.pageSize"
                    :page-sizes="[10, 20, 30, 50]"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="pagination.total"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    background
                  />
                </div>
              </el-row>
            </el-col>
            <el-col :span="12">
              <el-row>
                <div style="width: 100%" class="common-div-card main-table-right">
                  <el-table
                    class="steelCalss"
                    :data="expandTableData"
                    border
                    :header-cell-style="{ background: '#eef1f6', color: '#606266', textAlign: 'center' }"
                    :cell-style="{ textAlign: 'center' }"
                    :stripe="true"
                    v-loading="expandTableLoading"
                    :show-overflow-tooltip="true"
                  >
                    <el-table-column type="expand">
                      <template #default="speed">
                        <el-table :data="speed.row.speedClass" class="speedClass">
                          <el-table-column type="expand">
                            <template #default="detail">
                              <el-table :data="detail.row.detail" class="detailClass">
                                <el-table-column prop="extid" label="出口卷号" width="160" />
                                <el-table-column prop="entThk" label="入口厚度" width="120" />
                                <el-table-column prop="entWidth" label="入口宽度" width="120" />
                                <el-table-column prop="speed" label="速度" width="120" />
                                <el-table-column prop="giTem" label="GI锅温度" width="120" />
                                <el-table-column prop="p8Real" label="P8实际值" width="120" />
                                <el-table-column prop="p8Set" label="P8设定值" width="120" />
                                <el-table-column prop="p10Real" label="P10实际值" width="120" />
                                <el-table-column prop="p10Set" label="P10设定值" width="120" />
                                <el-table-column prop="p9Real" label="P9实际值" width="120" />
                                <el-table-column prop="p9Set" label="P9设定值" width="120" />
                                <el-table-column prop="zincLiquidVar" label="锌液方差" width="120" />
                                <el-table-column prop="zincLiquidStd" label="锌液标准差" width="120" />
                                <el-table-column prop="time" label="时间" width="220" />
                              </el-table>
                            </template>
                          </el-table-column>
                          <el-table-column type="index" label="序号" fixed="left" width="60" />
                          <!-- <el-table-column prop="steelGrade" label="钢种" /> -->
                          <el-table-column prop="speed" label="速度分档">
                            <template #default="scope"> {{ scope.row.speed }} </template>
                          </el-table-column>
                        </el-table>
                      </template>
                    </el-table-column>
                    <el-table-column type="index" label="序号" fixed="left" width="60" />
                    <el-table-column prop="steelGrade" label="钢种" />
                    <el-table-column prop="sum" label="数量" />
                  </el-table>
                </div>
              </el-row>
              <el-row>
                <!-- 分页区域 -->
                <div class="common-div-card pagination">
                  <el-pagination
                    v-model:current-page="pagination.currentPageR"
                    v-model:page-size="pagination.pageSizeR"
                    :page-sizes="[10, 20, 30, 50]"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="pagination.totalR"
                    @size-change="handleSizeRChange"
                    @current-change="handleCurrentRChange"
                    background
                  />
                </div>
              </el-row>
            </el-col>
          </el-row>
        </el-main>
        <el-footer>
          <div class="common-div-card footer-chart">
            <div class="chart-container" ref="chartRef"></div>
          </div>
        </el-footer>
      </el-container>
    </el-col>
  </div>
</template>
<script setup lang="ts">
  import { ref, reactive, computed, onMounted, onUnmounted, nextTick } from 'vue';
  import * as echarts from 'echarts/core';
  import { ElMessage } from 'element-plus';
  import { zincApi } from '/@/api/znpot/index';
  import dayjs from 'dayjs';

  interface SearchForm {
    start: string | Date;
    end: string | Date;
  }

  const searchForm = reactive<SearchForm>({
    start: dayjs().subtract(12, 'hours').format('YYYY-MM-DD HH:mm:ss'),
    end: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  });
  const leftTableData = ref<any[]>([]);
  const expandTableData = ref<any[]>([]);
  const leftTableLoading = ref(false);
  const expandTableLoading = ref(false);
  const tableRef = ref();
  const chartRef = ref<HTMLElement | null>(null);
  let chartInstance: echarts.ECharts | null = null;
  const graphDataX = ref<number[]>([]);
  const graphDataGI = ref<number[]>([]);
  const graphDataP8Real = ref<number[]>([]);
  const graphDataP8Set = ref<number[]>([]);
  const graphDataP10Real = ref<number[]>([]);
  const graphDataP10Set = ref<number[]>([]);

  // 分页数据
  const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
    currentPageR: 1,
    pageSizeR: 10,
    totalR: 0,
  });

  // 查询方法
  const handleSearch = () => {
    pagination.currentPage = 1;
    fetchData();
  };

  // 重置方法
  const handleReset = () => {
    (Object.keys(searchForm) as Array<keyof SearchForm>).forEach((key) => {
      searchForm[key] = '';
    });
    handleSearch();
  };

  // 分页大小变化
  const handleSizeChange = (val: number) => {
    pagination.pageSize = val;
    getLeftTableData();
  };

  // 页码变化
  const handleCurrentChange = (val: number) => {
    pagination.currentPage = val;
    getLeftTableData();
  };

  // 分页大小变化EXPAND
  const handleSizeRChange = (val: number) => {
    pagination.pageSizeR = val;
    getExpandData();
  };

  // 页码变化EXPAND
  const handleCurrentRChange = (val: number) => {
    pagination.currentPageR = val;
    getExpandData();
  };

  // 行点击事件
  const handleRowClick = async (row: any) => {
    if (!row.extid) {
      ElMessage.error('卷号为空无法查询');
      return;
    }
    const param = {
      line: 'CGL1870',
      extid: row.extid,
      curve: ['cgl_gi_znpot_temp', 'cgl_p8_temp_act', 'cgl_p8_temp_set', 'cgl_p10_temp_act', 'cgl_p10_temp_set'],
    };
    try {
      await zincApi.getGraph(param).then((res) => {
        graphDataGI.value = res.data.data.curve.cgl_gi_znpot_temp;
        graphDataP8Real.value = res.data.data.curve.cgl_p8_temp_act;
        graphDataP8Set.value = res.data.data.curve.cgl_p8_temp_set;
        graphDataP10Real.value = res.data.data.curve.cgl_p10_temp_act;
        graphDataP10Set.value = res.data.data.curve.cgl_p10_temp_set;
        graphDataX.value = [...Array(res.data.data.curve.cgl_gi_znpot_temp.length).keys()].map((i) => i + 1);
        updateCharts();
      });
    } catch (error: any) {
      console.error(error);
      ElMessage.error(error.message || '请求失败');
    }
  };

  const getLeftTableData = async () => {
    const param = {
      pageIndex: pagination.currentPage,
      pageSize: pagination.pageSize,
      condition: {
        begin: searchForm.start,
        end: searchForm.end,
      },
    };
    try {
      leftTableLoading.value = true;
      const res = await zincApi.getTableData(param);
      if (res.data.count == 0) {
        ElMessage.warning('当前查询到的数据为空');
        leftTableLoading.value = false;
        throw Error('当前查询到的数据为空');
      }
      if (res.data.status != 2000) {
        ElMessage.error('查询失败');
        leftTableLoading.value = false;
        throw Error('查询失败');
      }
      leftTableData.value = res.data.data.map((item: any) => ({
        extid: item.extid,
        steelGrade: item.steelgrade,
        entThk: item.enthk_class.toFixed(2),
        entWidth: item.enwidth_class.toFixed(2),
        speed: Math.round(item.cgl_process_speed_avg),
        giTem: item.cgl_gi_znpot_temp_avg.toFixed(2),
        p8Real: item.p8_act_avg.toFixed(2),
        p8Set: Math.round(item.p8_set_avg),
        p10Real: item.p10_act_avg.toFixed(2),
        p10Set: Math.round(item.p10_set_avg),
        p9Real: item.p9_act_avg.toFixed(2),
        p9Set: Math.round(item.p9_set_avg),
        zincLiquidVar: item.var_ye.toFixed(2),
        zincLiquidStd: item.std_ye.toFixed(2),
        time: item.toc,
      }));
      pagination.total = res.data.count;
      leftTableLoading.value = false;
      handleRowClick(leftTableData.value[0]);
    } catch (error: any) {
      leftTableLoading.value = false;
      console.error(error);
      // ElMessage.error(error.message || '请求失败');
    }
  };

  const getExpandData = async () => {
    try {
      expandTableLoading.value = true;
      const param = {
        pageIndex: pagination.currentPageR,
        pageSize: pagination.pageSizeR,
        condition: {
          begin: searchForm.start,
          end: searchForm.end,
        },
      };
      const res = await zincApi.getExpandData(param);
      expandTableData.value = formatExpandTableData(res.data.data);
      pagination.totalR = res.data.count;
      expandTableLoading.value = false;
    } catch (error: any) {
      expandTableLoading.value = false;
      console.error(error);
    }
  };

  const fetchData = async () => {
    getLeftTableData();
    getExpandData();
  };

  // -------------------------- 图表相关 --------------------------------

  const option = computed(() => ({
    title: {
      text: '锌锅温度超限曲线',
      textStyle: {
        fontSize: 16,
      },
      left: 'center',
      top: '5%',
    },
    backgroundColor: 'transparent',
    tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
    legend: {
      data: ['GI锅温度', 'p8实际温度', 'p8设定温度', 'p10实际温度', 'p10设定温度'],
      right: '4%',
      top: '8%', // Position at the top
      textStyle: {
        color: '#c0c4cc',
        fontSize: 10,
      },
      itemWidth: 15,
      itemHeight: 10,
    },
    grid: { left: '3%', right: '4%', bottom: '5%', top: '20%', containLabel: true }, // Increased top margin
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: graphDataX.value,
      axisLine: { lineStyle: { color: 'rgba(58, 90, 138, 0.5)' } },
      axisLabel: { color: '#c0c4cc', fontSize: 10 },
    },
    yAxis: {
      type: 'value',
      min: 38,
      max: 47,
      axisLabel: { color: '#c0c4cc', fontSize: 10 },
      splitLine: { lineStyle: { color: 'rgba(58, 90, 138, 0.3)' } },
      axisLine: { show: false },
    },
    series: [
      {
        name: 'GI锅温度',
        type: 'line',
        smooth: true,
        symbol: 'none',
        data: graphDataGI.value,
        // lineStyle: { color: '#00baff' },
        // areaStyle: {
        //   color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
        //     { offset: 0, color: 'rgba(0, 186, 255, 0.6)' },
        //     { offset: 1, color: 'rgba(0, 186, 255, 0.1)' },
        //   ]),
        // },
      },
      {
        name: 'p8实际温度',
        type: 'line',
        smooth: true,
        symbol: 'none',
        data: graphDataP8Real.value,
        // lineStyle: { color: '#00baff' },
        // areaStyle: {
        //   color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
        //     { offset: 0, color: 'rgba(0, 186, 255, 0.6)' },
        //     { offset: 1, color: 'rgba(0, 186, 255, 0.1)' },
        //   ]),
        // },
      },
      {
        name: 'p8设定温度',
        type: 'line',
        smooth: true,
        symbol: 'none',
        data: graphDataP8Set.value,
        // lineStyle: { color: '#00baff' },
        // areaStyle: {
        //   color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
        //     { offset: 0, color: 'rgba(0, 186, 255, 0.6)' },
        //     { offset: 1, color: 'rgba(0, 186, 255, 0.1)' },
        //   ]),
        // },
      },
      {
        name: 'p10实际温度',
        type: 'line',
        smooth: true,
        symbol: 'none',
        data: graphDataP10Real.value,
        // lineStyle: { color: '#00baff' },
        // areaStyle: {
        //   color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
        //     { offset: 0, color: 'rgba(0, 186, 255, 0.6)' },
        //     { offset: 1, color: 'rgba(0, 186, 255, 0.1)' },
        //   ]),
        // },
      },
      {
        name: 'p10设定温度',
        type: 'line',
        smooth: true,
        symbol: 'none',
        data: graphDataP10Set.value,
        // lineStyle: { color: '#00baff' },
        // areaStyle: {
        //   color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
        //     { offset: 0, color: 'rgba(0, 186, 255, 0.6)' },
        //     { offset: 1, color: 'rgba(0, 186, 255, 0.1)' },
        //   ]),
        // },
      },
    ],
  }));

  // --- 初始化图表 ---
  const initCharts = () => {
    try {
      if (chartRef.value && !chartInstance) {
        chartInstance = echarts.init(chartRef.value);
        chartInstance.setOption(option.value);
      }
    } catch (error) {
      console.error('图表初始化失败:', error);
    }
  };

  const resizeCharts = () => {
    chartInstance?.resize();
  };

  // --- 图表更新 ---
  const updateCharts = () => {
    option.value.xAxis.data = graphDataX.value;
    option.value.series[0].data = graphDataGI.value;
    option.value.series[1].data = graphDataP8Real.value;
    option.value.series[2].data = graphDataP8Set.value;
    option.value.series[3].data = graphDataP10Real.value;
    option.value.series[4].data = graphDataP10Set.value;
    option.value.yAxis.min = Math.floor(
      Math.min(
        ...(graphDataGI.value ?? []),
        ...(graphDataP8Real.value ?? []),
        ...(graphDataP8Set.value ?? []),
        ...(graphDataP10Real.value ?? []),
        ...(graphDataP10Set.value ?? [])
      ) - 5
    );
    option.value.yAxis.max = Math.floor(
      Math.max(
        ...(graphDataGI.value ?? []),
        ...(graphDataP8Real.value ?? []),
        ...(graphDataP8Set.value ?? []),
        ...(graphDataP10Real.value ?? []),
        ...(graphDataP10Set.value ?? [])
      ) + 15
    );
    chartInstance?.setOption(option.value, true);
  };

  onMounted(() => {
    fetchData();
    // 延迟初始化图表，确保DOM已渲染
    nextTick(() => {
      setTimeout(initCharts, 100);
    });

    window.addEventListener('resize', resizeCharts);
  });

  onUnmounted(() => {
    window.removeEventListener('resize', resizeCharts);
    chartInstance?.dispose();
  });

  // ------------------------------------------------------ expand table data 数据处理 --------------------------

  interface SpeedClassItem {
    speed: string;
    detail: any;
  }

  interface steelGradeItem {
    steelGrade: string;
    sum: number;
    speedClass: SpeedClassItem[];
  }

  function formatExpandTableData(data: any[]): steelGradeItem[] {
    const result: steelGradeItem[] = [];
    // 遍历外层钢种
    for (const [steelGrade, speedClasses] of Object.entries(data)) {
      const speedClassArray: SpeedClassItem[] = [];

      // 遍历内层速度分档
      let details: any;
      let speed: any;
      for ([speed, details] of Object.entries(speedClasses)) {
        speedClassArray.push({
          speed: speed,
          detail: details.map((item: any) => ({
            ...item,
            entThk: item.enthk_class ?? 0,
            entWidth: item.enwidth_class ?? 0,
            speed: Math.round(item.cgl_process_speed_avg),
            giTem: item.cgl_gi_znpot_temp_avg.toFixed(2),
            p8Real: item.p8_act_avg.toFixed(2),
            p8Set: Math.round(item.p8_set_avg),
            p10Real: item.p10_act_avg.toFixed(2),
            p10Set: Math.round(item.p10_set_avg),
            p9Real: item.p9_act_avg.toFixed(2),
            p9Set: Math.round(item.p9_set_avg),
            zincLiquidVar: item.var_ye.toFixed(2),
            zincLiquidStd: item.std_ye.toFixed(2),
            time: item.toc,
          })),
        });
      }
      result.push({
        steelGrade: steelGrade,
        sum: speedClassArray.length,
        speedClass: speedClassArray,
      });
    }

    return result;
  }
</script>
<style scoped lang="less">
  @border-radius: 8px;
  @primary-color: #2c69e8;
  @box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  @box-shadow-hover: 0 8px 32px rgba(0, 0, 0, 0.12);
  @border:1px solid #dcdfe6;

  .common-div-card {
    box-shadow: @box-shadow;
    transition: 0.3s;
    border-radius: @border-radius;
    border: @border;
    background-color: #fff;

    // 悬停状态
    &:hover {
      box-shadow: @box-shadow-hover;
    }
  }

  .overrun-page {
    width: 99vw;
    height: 100vh;
    background-color: #fff;

    &.linear-gradient {
      background-image: linear-gradient(to top, white, @primary-color) !important;
    }
  }

  .header-search {
    height: 8vh;
    display: flex;
    flex: 1;
    justify-content: flex-start;
    align-items: center;
    padding: 20px;
  }

  .header-search-form {
    display: flex;
    align-items: center;
    gap: 20px;
    padding: 8px 0 0 5px;
  }

  .main-table {
    height: 55vh;

    .main-table-left {
      padding: 10px;

      .el-table {
        height: calc(49vh - 20px);
      }
    }

    .main-table-right {
      padding: 10px;
      height: calc(49vh + 2px);

      .steelCalss {
        height: calc(49vh - 18px);
      }
    }
  }

  .pagination {
    width: 100%;
    height: 6vh;
    margin-top: 1vh;
    display: flex;
    justify-content: flex-end;
    padding: 10px;
  }

  .footer-chart {
    height: 30vh;
    width: 100%;
  }

  .chart-container {
    height: 100%;
    width: 100%;
  }
</style>
